package cn.zhiquxing.excel;

import cn.zhiquxing.vo.ImportData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Recover;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Service;
import org.springframework.web.client.ResourceAccessException;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

@Service
@Slf4j
public class ThirdPartyService {
    @Autowired
    private RestTemplate restTemplate;
    
    // 使用Spring Retry实现重试机制
    @Retryable(
        value = {RestClientException.class, ResourceAccessException.class},
        maxAttempts = 3,
        backoff = @Backoff(delay = 1000, multiplier = 2)
    )
    public ThirdPartyResponse callApi(ImportData data) {
        String apiUrl = "https://api.thirdparty.com/process";
        
        // 构建请求体
        ThirdPartyRequest request = new ThirdPartyRequest();
        request.setName(data.getName());
        request.setPhone(data.getPhone());
        request.setAddress(data.getAddress());
        
        // 设置超时时间
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<ThirdPartyRequest> entity = new HttpEntity<>(request, headers);
        
        // 发送请求
        ResponseEntity<ThirdPartyResponse> response = restTemplate.exchange(
            apiUrl, HttpMethod.POST, entity, ThirdPartyResponse.class);
        
        return response.getBody();
    }
    
    // 重试全部失败后的处理
    @Recover
    public ThirdPartyResponse recover(RuntimeException e, ImportData data) {
        log.error("第三方接口调用失败，数据: {}", data, e);
        ThirdPartyResponse response = new ThirdPartyResponse();
        response.setSuccess(false);
        response.setErrorMsg("服务不可用: " + e.getMessage());
        return response;
    }
}